package com.geniusk.security.utils;

import cn.hutool.crypto.digest.BCrypt;
import com.geniusk.common.enums.ResponseType;
import com.geniusk.common.exception.GraceException;
import com.geniusk.common.exception.IotException;
import com.geniusk.security.Interceptor.HeaderInterceptor;
import com.geniusk.security.core.LoginUser;

/**
 * 安全工具类
 */
public class SecurityUtil {

    /**
     * 用户ID
     **/
    public static Long getUserId() {
        try {
            return getLoginUser().getUserId();
        } catch (Exception e) {
            throw new IotException(ResponseType.UN_LOGIN);
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new IotException(ResponseType.UN_LOGIN);
        }
    }

    /**
     *获取登陆用户信息
     * @return 登陆用户信息
     */
    public static LoginUser getLoginUser(){
        LoginUser loginUser = HeaderInterceptor.currentUser.get();
        if(loginUser == null){
            GraceException.display(ResponseType.UN_LOGIN);
        }
        return loginUser;
    }

    /**
     * 生成BCryptPasswordEncoder密码
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        return BCrypt.hashpw(password);
    }

    /**
     * 判断密码是否相同
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        return BCrypt.checkpw(rawPassword, encodedPassword);
    }

}